<?PHP

class OP_TabbedContentWidget extends OP_WidgetTemplate{
	var $content_types = array(
		'posts'			=> array('title'=>'Posts','sortby'=> array('recent','popular','random')),
		'comments' 		=> array('title'=>'Comments','sortby'=>array('recent')),
		'tags' 			=> array('title'=>'Tags','sortby'=> array('cloud','count','name','recent','slug')),
		'categories'	=> array('title'=>'Categories','sortby'=> array('cloud','name')),
		'commenters' 	=> array('title'=>'Commenters','sortby'=>array('count','author','recent')),
		'forum'			=> array('title'=>'Forum', 'sortby'=> array('recent','popular','most viewed'))
	);
	
	/**
	 * render
	 * 
	 * Render Widget
	 * 
	 * @param array $args
	 * @param $widget_args
	 * @global $wpdb database resource
	 * @return void
	 **/
	function render(){
		if(!$current_modules = get_option('op_modules')){
			$current_modules = array();
			add_option('op_modules', $current_modules);
		}

		global $wpdb;
		
		$title = $this->values['title'];
		$quantity = 10;
		
		$feature_content = array();
		foreach($this->values['tabs'] as $tab){
			// Add forum to options if phpBB module is enabled
			if($tab['name'] == 'forum' && (!array_key_exists('phpBB',$current_modules) || $current_modules['phpBB'] != 1))
				continue;
				
			$subcontent = '';
			switch($tab['name']){
				case 'archives':
					break;
					
				case 'posts':
					$tab_name = 'Posts';
					
					switch($tab['sort']){
						case 0:
							$filter = 'date';
							$tab_name = 'Newest';
							break;
						case 1:
							$filter = 'comment_count';
							$tab_name = 'Most Discussed';
							break;
						case 2:
							$filter = 'rand';
							$tab_name = 'Random';
							break;
						default:
							$filter = 'date';
					}

					$posts = get_posts('numberposts='.$quantity.'&order=DESC&orderby='.$filter);
					foreach($posts as $post){
						$link = get_permalink($post->ID);
						$subcontent .= '<li><a href="'.$link.'">'.$post->post_title.'</a></li>';
					}
					
					break;
				
				case 'comments':
					if ( !$comments = wp_cache_get( 'recent_comments', 'widget' ) ) {
						$comments = $wpdb->get_results("SELECT comment_author, comment_author_url, comment_ID, comment_post_ID FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT $quantity");
						wp_cache_add( 'recent_comments', $comments, 'widget' );
					}
					foreach($comments as $comment){
						$subcontent .= '<li><a href="'. get_permalink($comment->comment_post_ID) . '#comment-' . $comment->comment_ID . '">Re: ' . get_the_title($comment->comment_post_ID) . '</a></li>';
					}
					$tab_name = 'Recent Comments';
					
					break;
					
				case 'forum':
					require_once(TEMPLATEPATH.'/op/modules/module.phpbb.php');
					$sortby = $values['sort']['forum'];
					$tab_name = 'Forum Posts';
					switch($tab['sort']){
						case 0:
							$filter = 'topic_last_post_id';
							break;
						case 1:
							$filter = 'topic_replies';
						case 2:
							$filter = 'topic_views';
					}
					
					$forum_posts = OP_phpBB3::getRecentPosts($filter);
					foreach($forum_posts as $forum_post){
						$subcontent .= '<li><a href="'.$forum_post['topic_url'].'">'.$forum_post['topic'].'</a> by '.$forum_post['author'].'</li>';
					}
					
					break;
					
				case 'tags':
					$tab_name = 'Tags';
					switch($tab['sort']){
						case 0:
						case 1:
							$orderby = 'count';
							$order = 'DESC';
							$tab_name = 'Popular Tags';
							break;
						
						case 2:
							$orderby = 'name';
							$order = 'ASC';
							break;
							
						case 2:
							$orderby = 'id';
							$order = 'DESC';
							$tab_name = 'Recent Tags';
							break;
							
						case 3:
							$orderby = 'slug';
							$order = 'ASC';
							break;
						
						default:
							$orderby = 'count';
							$order = 'DESC';
					}
					
					$tag_args = array( 'orderby' => $orderby, 'order' => $order );
					$tags = get_tags( $tag_args );
					
					$subcontent = '';
					if(count($tags) > 0){
						if($tab['sort'] == 0){
							$tab_name = 'Tag Cloud';
							$subcontent = wp_generate_tag_cloud($tags);
						}
						else{
							for($i = 0; $i < $quantity; $i++){
								$link = get_tag_link($tags[$i]->term_id);
								$subcontent .= '<li><a href="' . $link . '" rel="tag">' . $tags[$i]->name . '</a> ('.$tags[$i]->count.')</li>';
							}							
						}
					}

					break;
				
				case 'categories':
					$tab_name = 'Categories';
					$categories = get_categories();
					
					$subcontent = '';
					if(count($categories) > 0){
						if($tab['sort'] == 0){
							$tab_name = 'Category Cloud';
							$subcontent = wp_generate_tag_cloud($categories);
						}
						else{
							for($i = 0; $i < $quantity; $i++){
								$link = get_category_link($categories[$i]->term_id);
								$subcontent .= '<li><a href="' . $link . '" rel="tag">' . $categories[$i]->name . '</a> ('.$categories[$i]->count.')</li>';
							}
						}
					}
					break;
					
				case 'commenters':
					$tab_name = 'Top Commenters';
					switch($tab['sort']){
						case 0:
							$orderby = 'comment_count';
							$order = 'DESC';
							break;
						
						case 1:
							$orderby = 'comment_author';
							$order = 'ASC';
							break;
						
						case 2:
							$orderby = 'MAX(comment_id)';
							$order = 'DESC';
							$tab_name = 'Recent Commenters';
							break;
														
						default:
							$orderby = 'comment_count';
							$order = 'DESC';
					}
					
					// If we want to add capability to filter out site authors
					//SELECT * FROM $wpdb->users WHERE ID IN (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = 'wp_user_level' AND meta_value > 1);
					
					$sql = 	"SELECT comment_author, comment_author_url, comment_author_email, COUNT(comment_author) AS comment_count
						FROM $wpdb->comments
						WHERE comment_type != 'pingback'
						AND comment_approved = '1'
      					GROUP BY comment_author_email
      					ORDER BY $orderby $order
      					LIMIT $quantity";

					$commenters = $wpdb->get_results($sql);
					
					foreach($commenters as $commenter){
						if(strlen($commenter->comment_author_url) == 0){
							$subcontent .= '<li>' . $commenter->comment_author . ' ('.$commenter->comment_count.')</li>';	
						}
						else{
							$subcontent .= '<li><a href="'. $commenter->comment_author_url . '">' . $commenter->comment_author . '</a> ('.$commenter->comment_count.')</li>';	
						}
					}
					
					break;
				
				case 'user_func':
					if(function_exists($tab['sort'])){
						$result = call_user_func($tab['sort']);
						$tab_name = $result['name'];
						$subcontent = $result['content'];
					}
					break;
					
			}
			
			if(isset($tab_name)){
				$feature_content[] = array(
					'name'		=> $tab_name,
					'content'	=> $subcontent
				);
			}
		}

		include(TEMPLATEPATH.'/widgets/template.tabbed_content.php');

	}
	
	function do_post($post){
		$tabs = array();

		$post['tab']['tag'] = array_diff($post['tab']['type'],array(''));
		$post['tab']['tag'] = array_merge($post['tab']['tag'],array());
		$post['tab']['sortby'] = array_diff($post['tab']['sortby'],array(''));
		$post['tab']['sortby'] = array_merge($post['tab']['sortby'],array());

		for($i=0; $i < count($post['tab']['tag']); $i++){
			if($post['tab']['tag'][$i] == '') continue;
			else{
				$tabs[] = array(
					'name'	=>	$post['tab']['tag'][$i],
					'sort'	=>	attribute_escape($post['tab']['sortby'][$i])
				);
			}
		}
		$title = attribute_escape($post['title']);
		return compact('tabs', 'sort', 'title' );
	}
	
	function options(){
		echo '<p>',
			'<p><label for="widget_op_tabbed_content-title-'.$this->values['number'].'">'._e('Title:').' <input class="widefat" id="widget_op_tabbed_content-title-'.$this->values['number'].'" name="widget_op_tabbed_content['.$this->values['number'].'][title]" type="text" value="'.$this->values['title'].'" /></label></p>',
			'<div><a href="#" class="op_add_tab_trigger">+ Add Tab</a></div>',
			'<div class="tab_options" style="display:none">',
			'<a href="#" class="op_remove_tab_trigger">X</a>';

		echo '<label>Select type: </label><select name="widget_op_tabbed_content['.$this->values['number'].'][tab][type][]" class="sortby_extra_trigger">',
			'<option></option>';
		
		foreach($this->content_types as $k=>$content){
			echo '<option value="'.$k.'">'.$content['title'].'</option>';
		}
		echo '<option value="user_func">User Function</option>';
		echo '</select>',
			'</div>';

		echo '<span class="sort_options" style="display:none">';
		
		foreach($this->content_types as $content){	
			if(isset($content['sortby'])){
				echo '<span class="sort_options_child sort_options_'.strtolower($content['title']).'"> sort by <select name="widget_op_tabbed_content['.$number.'][tab][sortby][]">',
					'<option></option>';
				for($i=0; $i < count($content['sortby']); $i++){
					echo '<option value="'.$i.'">'.$content['sortby'][$i].'</option>';
				}
				echo '</select></span>';
			}
		}
		echo '<span class="sort_options_child sort_options_user_func"> ',
			_e('Hook Name:').' <input type="text" style="width: 95px;" name="widget_op_tabbed_content['.$this->values['number'].'][tab][sortby][]">',
			'</span>';
		echo '</span>';		

		echo '<div class="op_tabbed_content op_current_tabs">';
		if(count($this->values['tabs'])>0){
			// loop through all of the tabs saved
			foreach($this->values['tabs'] as $tab){
				echo '<div class="tab_options">',
					'<a href="#" class="op_remove_tab_trigger">X</a>',
					'<label>Select type: </label><select name="widget_op_tabbed_content['.$this->values['number'].'][tab][type][]" class="sortby_extra_trigger">',
					'<option></option>';
				
				// Add content types to drop down
				foreach($this->content_types as $k=>$content){
					$selected = $tab['name'] == strtolower($content['title']) ? ' selected' : '';
					echo '<option value="'.$k.'"'.$selected.'>'.$content['title'].'</option>';
				}
				echo '<option value="user_func"'.($tab['name'] == 'user_func' ? ' selected' : '').'>User Function</option>';
				echo '</select>';
				
				if(isset($this->content_types[$tab['name']]['sortby'])){
					echo '<span class="sort_options_child sort_options_'.strtolower($content['title']).'"> sort by <select name="widget_op_tabbed_content['.$this->values['number'].'][tab][sortby][]">',
						'<option></option>';
					foreach($this->content_types[$tab['name']]['sortby'] as $k => $sort_option){
						$selected = $tab['sort'] == $k ? ' selected' : '';
						echo '<option value="'.$k.'"'.$selected.'>'.$sort_option.'</option>';
					}
					echo '</select></span>';
				}
				else{
					echo '<span class="sort_options_child sort_options_user_func"> ',
					 	_e('Hook Name:').' <input type="text" style="width: 95px;" name="widget_op_tabbed_content['.$this->values['number'].'][tab][sortby][]" value="'.$tab['sort'].'">',
					 	'</span>';
				}
						
				echo '</div>';
			}
		}
		echo '</div>',
			'</p>';
	}
	
	
	function head()
	{
		$url = get_bloginfo('template_directory').'/';
		wp_register_script('optabbedcontentjs', $url.'scripts/tabbed_content.js',array('onepressjs'));
		wp_enqueue_script('optabbedcontentjs');
	}
	
	/**
	 * Add styles and javascript for widget admin
	 *
	 * @return void
	 * @author Sean
	 **/
	function admin_head(){
		$url = get_bloginfo('template_directory').'/op/admin/';
		wp_register_script('opfeaturettetabsadminjs', $url.'scripts/featurette_tabs.js',array('jquery','jquery-ui-sortable','opw'));
		wp_enqueue_script('opfeaturettetabsadminjs');
		wp_register_style('opfeaturettetabsadmin',$url.'styles/featurette_tabs.css');
		wp_enqueue_style('opfeaturettetabsadmin');
	}
}

$widget = new OP_Widget('tabbed_content');
$widget->setMeta('OP Tabbed Content',"A tabbed content widget for your blog");
$widget->setDefaults(array('title'=>''));
$widget->setAdminDimensions(415,350);

$opw_tabbed_content = new OP_TabbedContentWidget($widget);
add_action('widgets_init', array($opw_tabbed_content, 'init'));

?>